﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MySql.Data.MySqlClient;
using MySql.Data.Types;
using TAMS;

namespace TAMS.Faculty_Member
{
    public partial class Research_Del : System.Web.UI.Page
    {
        MySqlConnection conn;
        MySqlCommand sqlCommand;
        MySqlDataReader readVals;
        string strProvider = Resource1.databaseConnection;
        string id;

        protected void Page_Load(object sender, EventArgs e)
        {
            ((Menu)Master.FindControl("Menu1")).Items[3].Selected = true;
            
            id = (string)Session["userName"];

            if (id == null)
                Response.Redirect("../login.aspx");

            // Connect to the Database
            conn = new MySqlConnection(strProvider);
            conn.Open();

            string strSQL = "SELECT R.rid AS \"Research Id\", R.about \"Topic\", R.r_since \"Since\" " +
                            "FROM Research R, Researches RS " +
                            "WHERE RS.fmem_fsid = " + id + " AND R.rid = RS.rid";

            sqlCommand = new MySqlCommand(strSQL, conn);
            readVals = sqlCommand.ExecuteReader();

            if (!IsPostBack)
            {
                MainTable.DataSource = readVals;
                MainTable.DataBind();
                MainTable.SelectedIndex = 0;
            }

            conn.Close();
        }

        protected void select_clicked(object sender, EventArgs e)
        {

        }

        protected void delete_clicked(object sender, EventArgs e)
        {
            id = (string)Session["userName"];

            if (id == null)
                Response.Redirect("../login.aspx");

            // Connect to the Database
            conn = new MySqlConnection(strProvider);
            conn.Open();

            string rid = MainTable.SelectedRow.Cells[1].Text;

            string strSQL = "DELETE FROM Research WHERE rid = " + rid;

            try
            {
                sqlCommand = new MySqlCommand(strSQL, conn);
                sqlCommand.ExecuteNonQuery();
            }
            catch (MySqlException ex)
            {
                string msg = "Delete Error:";
                msg += ex.Message;
                ErrorLabel.Text = msg;
                ErrorLabel.Visible = true;
                goto end;
            }
            ErrorLabel.Text = "Successfully Deleted!";

        end:
            conn.Close();
            Response.Redirect("Fac_Research_Del.aspx");

        }
    }
}